package com.tankbattle.view;

import javax.swing.JFrame;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.event.KeyEvent;
import java.awt.KeyboardFocusManager;

/**
 * 游戏窗口类，继承自JFrame
 */
public class GameWindow extends JFrame {
    
    private GamePanel gamePanel;
    
    public GameWindow() throws HeadlessException {
        // 设置窗口标题
        setTitle("坦克大战");
        
        // 设置窗口关闭操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // 移除窗口装饰
        setUndecorated(true);

        // 创建游戏面板实例
        gamePanel = new GamePanel();
        
        // 将游戏面板添加到窗口中
        add(gamePanel);
        
        // 获取屏幕设备
        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();

        // 设置为全屏
        gd.setFullScreenWindow(this);

        // 启动游戏循环
        gamePanel.startGameLoop();

        // 确保面板获得焦点
        gamePanel.requestFocusInWindow();

        // 添加全局键盘监听
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(e -> {
            if (e.getID() == KeyEvent.KEY_PRESSED) {
                if (e.getKeyChar() == 'q' || e.getKeyChar() == 'Q') {
                    // 停止游戏循环
                    gamePanel.stopGameLoop();
                    // 退出全屏
                    gd.setFullScreenWindow(null);
                    // 关闭程序
                    System.exit(0);
                }
            }
            return false;
        });
    }
}
